package com.niguang.common.interceptor;

import com.alibaba.fastjson.JSON;
import com.niguang.common.constant.ResultCode;
import com.niguang.common.pojo.Result;
import com.niguang.common.util.ApiTokenUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.util.ObjectUtils;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;


/**
 * @author
 */
@Slf4j
@Component
public class ApiTokenInterceptor implements HandlerInterceptor {

    @Autowired
    private ApiTokenUtils apiTokenUtils;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object o) throws Exception {

        if (RequestMethod.OPTIONS.toString().equals(request.getMethod())) {
            return true;
        }

        final String unionId = request.getHeader("unionId");
        log.debug("authHeader unionId：{}", unionId);
        if (StringUtils.isNotBlank(unionId)) {
            return true;
        }

        final String authHeader = request.getHeader("Authorization");
        log.debug("authHeader--{}", authHeader);
        if (StringUtils.isBlank(authHeader)) {
            resultMessage("Invalid Authorization header", response);
            return false;
        }


        if (ObjectUtils.isEmpty(apiTokenUtils.getUserId())) {
            resultMessage("Authorization Invalid ", response);
            return false;
        }

        return true;

    }


    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {

    }


    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {

    }

    private void resultMessage(String msg, HttpServletResponse response) {
        try {
            String resultJson = JSON.toJSONString(Result.build(ResultCode.UNAUTHORIZED, msg));
            response.setCharacterEncoding("UTF-8");
            response.setContentType("application/json");
            response.getWriter().write(resultJson);
        } catch (IOException e) {
            log.error("写入响应消息异常!", e);
        }
    }


}
